#!/bin/bash

# 鱼C论坛闪拍监控 - systemd服务安装脚本
# 作者: SOLO Coding
# 用途: 安装和配置systemd服务

set -e  # 遇到错误立即退出

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "=== 鱼C论坛闪拍监控 - systemd服务安装 ==="
echo "安装时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "工作目录: $SCRIPT_DIR"
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "❌ 此脚本需要root权限运行"
    echo "请使用: sudo $0"
    exit 1
fi

# 检查systemd是否可用
if ! command -v systemctl &> /dev/null; then
    echo "❌ 系统不支持systemd"
    exit 1
fi

# 检查服务文件是否存在
if [ ! -f "fishc-monitor.service" ]; then
    echo "❌ 未找到服务文件: fishc-monitor.service"
    exit 1
fi

echo "📋 当前配置信息:"
echo "  工作目录: $SCRIPT_DIR"
echo "  Python路径: $(which python3)"
echo "  当前用户: $(whoami)"
echo ""

# 询问运行用户
read -p "请输入运行服务的用户名 [默认: $SUDO_USER]: " SERVICE_USER
SERVICE_USER=${SERVICE_USER:-$SUDO_USER}

if [ -z "$SERVICE_USER" ]; then
    echo "❌ 必须指定运行用户"
    exit 1
fi

# 检查用户是否存在
if ! id "$SERVICE_USER" &>/dev/null; then
    echo "❌ 用户 $SERVICE_USER 不存在"
    exit 1
fi

echo "✅ 将使用用户: $SERVICE_USER"
echo ""

# 创建临时服务文件
TEMP_SERVICE="/tmp/fishc-monitor.service"
cp "fishc-monitor.service" "$TEMP_SERVICE"

# 替换路径和用户
sed -i "s|/home/fishc/fishcwatcher|$SCRIPT_DIR|g" "$TEMP_SERVICE"
sed -i "s|User=fishc|User=$SERVICE_USER|g" "$TEMP_SERVICE"
sed -i "s|Group=fishc|Group=$SERVICE_USER|g" "$TEMP_SERVICE"

echo "🔧 配置服务文件..."

# 复制服务文件到systemd目录
cp "$TEMP_SERVICE" "/etc/systemd/system/fishc-monitor.service"
rm "$TEMP_SERVICE"

echo "✅ 服务文件已安装: /etc/systemd/system/fishc-monitor.service"

# 设置文件权限
chown "$SERVICE_USER:$SERVICE_USER" "$SCRIPT_DIR" -R
chmod +x "$SCRIPT_DIR"/*.sh

echo "✅ 文件权限已设置"

# 重新加载systemd
echo "🔄 重新加载systemd配置..."
systemctl daemon-reload

echo "✅ systemd配置已重新加载"
echo ""
echo "=== 安装完成 ==="
echo ""
echo "🎉 服务安装成功！"
echo ""
echo "📋 服务管理命令:"
echo "  sudo systemctl start fishc-monitor     # 启动服务"
echo "  sudo systemctl stop fishc-monitor      # 停止服务"
echo "  sudo systemctl restart fishc-monitor   # 重启服务"
echo "  sudo systemctl enable fishc-monitor    # 开机自启"
echo "  sudo systemctl disable fishc-monitor   # 取消自启"
echo "  sudo systemctl status fishc-monitor    # 查看状态"
echo "  sudo journalctl -u fishc-monitor -f    # 查看日志"
echo ""
echo "💡 建议操作:"
echo "1. 启用开机自启: sudo systemctl enable fishc-monitor"
echo "2. 启动服务:     sudo systemctl start fishc-monitor"
echo "3. 检查状态:     sudo systemctl status fishc-monitor"
echo ""